<script lang="ts" setup>
// @ts-ignore
import type { VbenDrawerInst } from '@vben/common-ui';
import type { UserQueryParams } from '#/api/system/user';

import { ElMessage, ElSteps, ElStep, ElProgress, ElUpload, ElLink } from 'element-plus';
import { Upload, Download } from '@vben/icons';
import { ref, unref, reactive } from 'vue';

import { useVbenForm } from '#/adapter/form';
import { exportUsers, importUsers } from '#/api/system/user';
import { $t } from '#/locales';
import { useGridFormSchema } from '../data';

const emit = defineEmits(['success', 'register']);

const mode = ref<'import' | 'export'>('export');
const loading = ref(false);
const currentStep = ref(0);
const uploadFile = ref<File | null>(null);
const importResult = ref<{ total: number; success: number; fail: number } | null>(null);
const exportParams = reactive<UserQueryParams>({});
const exportProgress = ref(0);
const exportUrl = ref('');

// 表单实例
// @ts-ignore
const [Form, formApi] = useVbenForm({
  submitter: false,
});

// 表单模式
const schema = useGridFormSchema();

// 处理模式切换
const handleModeChange = (newMode: 'import' | 'export') => {
  mode.value = newMode;
  currentStep.value = 0;
  uploadFile.value = null;
  importResult.value = null;
  exportProgress.value = 0;
  exportUrl.value = '';
};

// 处理上传前检查
const beforeUpload = (file: File) => {
  const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
  const isLt5M = file.size / 1024 / 1024 < 5;

  if (!isExcel) {
    ElMessage.error($t('system.user.importFormatError'));
    return false;
  }
  if (!isLt5M) {
    ElMessage.error($t('system.user.importSizeError'));
    return false;
  }

  uploadFile.value = file;
  return false; // 阻止自动上传
};

// 导入用户
const handleImport = async () => {
  if (!uploadFile.value) {
    ElMessage.warning($t('system.user.selectFileFirst'));
    return;
  }

  try {
    loading.value = true;

    const formData = new FormData();
    formData.append('file', uploadFile.value);

    importResult.value = await importUsers(formData);
    currentStep.value = 2;

    if (importResult.value.success > 0) {
      emit('success');
    }
  } catch (error) {
    console.error('导入用户失败:', error);
    ElMessage.error($t('system.user.importFailed'));
  } finally {
    loading.value = false;
  }
};

// 导出用户
const handleExport = async () => {
  try {
    loading.value = true;
    currentStep.value = 1;

    // 模拟进度
    const timer = setInterval(() => {
      if (exportProgress.value < 90) {
        exportProgress.value += 10;
      }
    }, 300);

    // 获取表单值
    // @ts-ignore
    const values = formApi.getValues();

    // 处理日期范围
    if (values.createdTime && Array.isArray(values.createdTime) && values.createdTime.length === 2) {
      values.startTime = values.createdTime[0];
      values.endTime = values.createdTime[1];
      delete values.createdTime;
    }

    const blob = await exportUsers(values);

    // 完成进度
    clearInterval(timer);
    exportProgress.value = 100;

    // 创建下载链接
    const url = window.URL.createObjectURL(blob);
    exportUrl.value = url;

    // 创建下载链接并点击
    const link = document.createElement('a');
    link.href = url;
    link.download = `用户数据_${new Date().toISOString().split('T')[0]}.xlsx`;
    link.click();

    currentStep.value = 2;
  } catch (error) {
    console.error('导出用户失败:', error);
    ElMessage.error($t('system.user.exportFailed'));
  } finally {
    loading.value = false;
  }
};

// 关闭抽屉
function closeDrawer() {
  const drawerInstance = unref(drawerDialogRef);
  if (drawerInstance) {
    drawerInstance.closeDrawer();
  }
}

const drawerDialogRef = ref<VbenDrawerInst | null>(null);

// @ts-ignore
function register(instance) {
  drawerDialogRef.value = instance;
  emit('register', instance);
}

// 打开抽屉时的处理
// @ts-ignore
function onDrawerOpened(data) {
  // 可以根据data设置初始模式
  if (data && data.mode) {
    handleModeChange(data.mode);
  }
}

defineExpose({
  setData: onDrawerOpened,
});
</script>

<template>
  <VbenDrawer
    v-bind="$attrs"
    @register="register"
    :title="$t('system.user.importExport')"
    width="700px"
    :loading="loading"
  >
    <div class="mode-switch mb-6">
      <el-radio-group v-model="mode" @change="handleModeChange">
        <el-radio-button value="export">{{ $t('system.user.export') }}</el-radio-button>
        <el-radio-button value="import">{{ $t('system.user.import') }}</el-radio-button>
      </el-radio-group>
    </div>

    <ElSteps :active="currentStep" finish-status="success" class="mb-6">
      <ElStep v-if="mode === 'export'" :title="$t('system.user.exportStep1')" />
      <ElStep v-if="mode === 'import'" :title="$t('system.user.importStep1')" />
      <ElStep :title="$t('system.user.processing')" />
      <ElStep :title="$t('system.user.completed')" />
    </ElSteps>

    <div class="step-content">
      <!-- 导出 - 步骤1：选择过滤条件 -->
      <div v-if="mode === 'export' && currentStep === 0">
        <h3 class="step-title mb-4">{{ $t('system.user.exportFilterTitle') }}</h3>
        <p class="text-gray-500 mb-4">{{ $t('system.user.exportFilterDesc') }}</p>

        <Form :schema="schema" />

        <div class="text-center mt-6">
          <el-button type="primary" @click="handleExport" :loading="loading">
            <Download class="mr-1" />
            {{ $t('system.user.startExport') }}
          </el-button>
        </div>
      </div>

      <!-- 导入 - 步骤1：上传文件 -->
      <div v-if="mode === 'import' && currentStep === 0">
        <h3 class="step-title mb-4">{{ $t('system.user.importUploadTitle') }}</h3>
        <p class="text-gray-500 mb-4">{{ $t('system.user.importUploadDesc') }}</p>

        <div class="upload-container">
          <ElUpload
            class="upload-dragger"
            drag
            action=""
            :auto-upload="false"
            :on-change="(file) => beforeUpload(file.raw)"
            :limit="1"
            :show-file-list="true"
          >
            <Upload class="upload-icon" />
            <div class="el-upload__text">
              {{ $t('system.user.dropFileHere') }}<em>{{ $t('system.user.clickToUpload') }}</em>
            </div>
            <template #tip>
              <div class="upload-tip">
                {{ $t('system.user.importFileTip') }}
                <ElLink type="primary">{{ $t('system.user.downloadTemplate') }}</ElLink>
              </div>
            </template>
          </ElUpload>
        </div>

        <div class="file-info mt-4" v-if="uploadFile">
          <p>{{ $t('system.user.selectedFile') }}: {{ uploadFile.name }}</p>
          <p>{{ $t('system.user.fileSize') }}: {{ (uploadFile.size / 1024).toFixed(2) }} KB</p>
        </div>

        <div class="text-center mt-6">
          <el-button type="primary" @click="handleImport" :loading="loading" :disabled="!uploadFile">
            <Upload class="mr-1" />
            {{ $t('system.user.startImport') }}
          </el-button>
        </div>
      </div>

      <!-- 处理中 -->
      <div v-if="currentStep === 1">
        <h3 class="step-title mb-4">
          {{ mode === 'export' ? $t('system.user.exportProcessing') : $t('system.user.importProcessing') }}
        </h3>

        <div class="progress-container">
          <ElProgress
            :percentage="mode === 'export' ? exportProgress : 50"
            :status="loading ? '' : 'success'"
          />
          <p class="text-center mt-2">
            {{ mode === 'export' ? $t('system.user.exportProgressTip') : $t('system.user.importProgressTip') }}
          </p>
        </div>
      </div>

      <!-- 完成 -->
      <div v-if="currentStep === 2">
        <h3 class="step-title mb-4">
          {{ mode === 'export' ? $t('system.user.exportCompleted') : $t('system.user.importCompleted') }}
        </h3>

        <!-- 导出结果 -->
        <div v-if="mode === 'export'" class="result-container">
          <p>{{ $t('system.user.exportCompletedDesc') }}</p>

          <div class="text-center mt-4" v-if="exportUrl">
            <el-button type="success" @click="() => window.open(exportUrl, '_blank')">
              <Download class="mr-1" />
              {{ $t('system.user.downloadAgain') }}
            </el-button>
          </div>
        </div>

        <!-- 导入结果 -->
        <div v-if="mode === 'import' && importResult" class="result-container">
          <div class="import-stats">
            <ElDescriptions border :column="1">
              <ElDescriptionsItem :label="$t('system.user.totalRecords')">
                {{ importResult.total }}
              </ElDescriptionsItem>
              <ElDescriptionsItem :label="$t('system.user.successRecords')">
                <span class="text-success">{{ importResult.success }}</span>
              </ElDescriptionsItem>
              <ElDescriptionsItem :label="$t('system.user.failedRecords')">
                <span class="text-danger">{{ importResult.fail }}</span>
              </ElDescriptionsItem>
            </ElDescriptions>
          </div>
        </div>
      </div>
    </div>
  </VbenDrawer>
</template>

<style scoped>
.step-title {
  font-size: 16px;
  font-weight: 500;
  color: var(--el-text-color-primary);
}

.upload-container {
  width: 100%;
  margin: 20px 0;
}

.upload-dragger {
  width: 100%;
}

.upload-icon {
  font-size: 48px;
  color: #909399;
  margin-bottom: 10px;
}

.upload-tip {
  margin-top: 10px;
  color: var(--el-text-color-secondary);
}

.progress-container {
  padding: 20px;
}

.result-container {
  padding: 20px;
}

.import-stats {
  margin-top: 20px;
}

.text-success {
  color: var(--el-color-success);
}

.text-danger {
  color: var(--el-color-danger);
}
</style>
